package org.dromara.web.service.auth.impl;

import cn.dev33.satoken.secure.BCrypt;
import cn.dev33.satoken.stp.SaLoginModel;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.checkerframework.checker.units.qual.A;
import org.dromara.common.core.constant.Constants;
import org.dromara.common.core.constant.GlobalConstants;
import org.dromara.common.core.constant.TenantConstants;
import org.dromara.common.core.domain.dto.RoleDTO;
import org.dromara.common.core.domain.model.LoginUser;
import org.dromara.common.core.domain.model.PasswordLoginBody;
import org.dromara.common.core.enums.ClientTypeEnum;
import org.dromara.common.core.enums.LoginType;
import org.dromara.common.core.enums.UserStatus;
import org.dromara.common.core.enums.UserType;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.common.core.exception.user.CaptchaException;
import org.dromara.common.core.exception.user.CaptchaExpireException;
import org.dromara.common.core.exception.user.UserException;
import org.dromara.common.core.utils.MessageUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.core.utils.ValidatorUtils;
import org.dromara.common.json.utils.JsonUtils;
import org.dromara.common.redis.utils.RedisUtils;
import org.dromara.common.satoken.utils.LoginHelper;
import org.dromara.common.web.config.properties.CaptchaProperties;
import org.dromara.dao.business.domain.User;
import org.dromara.dao.business.domain.XiaozhiSysUser;
import org.dromara.dao.business.domain.XiaozhiSysUserToken;
import org.dromara.dao.business.mapper.UserMapper;
import org.dromara.dao.business.mapper.XiaozhiSysUserMapper;
import org.dromara.dao.business.mapper.XiaozhiSysUserTokenMapper;
import org.dromara.dao.system.domain.SysUser;
import org.dromara.dao.system.domain.vo.SysClientVo;
import org.dromara.dao.system.domain.vo.SysUserVo;
import org.dromara.dao.system.mapper.SysUserMapper;
import org.dromara.web.domain.vo.LoginVo;
import org.dromara.web.exception.user.PasswordWrongException;
import org.dromara.web.service.auth.IAuthStrategy;
import org.dromara.web.service.auth.SysLoginService;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

/**
 * 密码认证策略
 *
 * @author Michelle.Chung
 */
@Slf4j
@Service("password" + IAuthStrategy.BASE_NAME)
@RequiredArgsConstructor
public class PasswordAuthStrategy implements IAuthStrategy {

    private final CaptchaProperties captchaProperties;
    private final SysLoginService loginService;
    private final SysUserMapper sysUserMapper;
    private final UserMapper userMapper;
    private final XiaozhiSysUserMapper xiaozhiSysUserMapper;
    private final XiaozhiSysUserTokenMapper xiaozhiSysUserTokenMapper;

    @Override
    public LoginVo login(String body, SysClientVo client) {
        PasswordLoginBody loginBody = JsonUtils.parseObject(body, PasswordLoginBody.class);


        LoginUser loginUser = null;
        if (ClientTypeEnum.ADMIN.equals(client.getClientKey())) {
            loginUser = adminLogin(loginBody, client);
        } else if (ClientTypeEnum.APP.equals(client.getClientKey())) {
            loginUser = appLogin(loginBody, client);
        }

        SaLoginModel model = new SaLoginModel();
        model.setDevice(client.getDeviceType());
        // 自定义分配 不同用户体系 不同 token 授权时间 不设置默认走全局 yml 配置
        // 例如: 后台用户30分钟过期 app用户1天过期
        model.setTimeout(client.getTimeout());
        model.setActiveTimeout(client.getActiveTimeout());
        model.setExtra(LoginHelper.CLIENT_KEY, client.getClientId());
        // 生成token
        LoginHelper.login(loginUser, model);

        LoginVo loginVo = new LoginVo();
        loginVo.setAccessToken(StpUtil.getTokenValue());
        loginVo.setExpireIn(StpUtil.getTokenTimeout());
        loginVo.setClientId(client.getClientId());

        if (ClientTypeEnum.APP.equals(client.getClientKey())) {
            String token = loginVo.getAccessToken();
            XiaozhiSysUserToken tokenEntity = xiaozhiSysUserTokenMapper.getByUserId(loginUser.getUserId());
            if (tokenEntity == null) {

                tokenEntity = new XiaozhiSysUserToken();
                tokenEntity.setUserId(loginUser.getUserId());
                tokenEntity.setToken(token);
                tokenEntity.setUpdateDate(LocalDateTime.now());
                tokenEntity.setExpireDate(LocalDateTime.now().plusMonths(12));
                // 保存token
                xiaozhiSysUserTokenMapper.insert(tokenEntity);
            } else {
                tokenEntity.setToken(token);
                tokenEntity.setUpdateDate(LocalDateTime.now());
                tokenEntity.setExpireDate(LocalDateTime.now().plusMonths(12));

                // 更新token
                xiaozhiSysUserTokenMapper.updateById(tokenEntity);
            }
        }

        return loginVo;
    }



    private LoginUser adminLogin(PasswordLoginBody loginBody, SysClientVo client) {

        ValidatorUtils.validate(loginBody);
//        String tenantId = loginBody.getTenantId();
        String username = loginBody.getUsername();
        String password = loginBody.getPassword();
        String code = loginBody.getCode();
        String uuid = loginBody.getUuid();

        boolean captchaEnabled = captchaProperties.getEnable();
        // 验证码开关
        if (captchaEnabled) {
            validateCaptcha( username, code, uuid);
        }
        SysUserVo user = loadUserByUsername(username);
//        loginService.checkLogin(LoginType.PASSWORD, tenantId, username, () -> !BCrypt.checkpw(password, user.getPassword()));
        loginService.checkLogin(LoginType.PASSWORD,username, () -> !password.equals(user.getPassword()));
        // 此处可根据登录用户的数据不同 自行创建 loginUser
        LoginUser loginUser =  loginService.buildLoginUser(user);
        loginUser.setClientKey(client.getClientKey());
        loginUser.setDeviceType(client.getDeviceType());
        return loginUser;
    }


    public LoginUser appLogin(PasswordLoginBody loginBody, SysClientVo client) {
        ValidatorUtils.validate(loginBody);
//        String tenantId = loginBody.getTenantId();
        String username = loginBody.getUsername();
        String password = loginBody.getPassword();

        User user = userMapper.selectOne(new LambdaQueryWrapper<User>()
            .eq(User::getUsername, username)
        );

        if (user == null) {
            throw new UserException("user.not.exists", username);
        }
        if (user.getStatus() != null && !user.getStatus()) {
            throw new UserException("user.blocked", username);
        }
        if (!password.equals(user.getPassword())) {
            throw new UserException("user.password.wrong");
        }

        XiaozhiSysUser xiaozhiSysUser = xiaozhiSysUserMapper.selectById(user.getId());
        if (xiaozhiSysUser == null) {
            xiaozhiSysUser = new XiaozhiSysUser();
            xiaozhiSysUser.setId(user.getId());
            xiaozhiSysUser.setUsername(user.getUsername());
            xiaozhiSysUser.setPassword(BCrypt.hashpw(user.getPassword()));
            xiaozhiSysUser.setStatus(true);
            xiaozhiSysUser.setSuperAdmin(false);
            xiaozhiSysUser.setCreateDate(LocalDateTime.now());
            xiaozhiSysUser.setUpdateDate(LocalDateTime.now());
            xiaozhiSysUserMapper.insert(xiaozhiSysUser);

        }

        LoginUser loginUser = new LoginUser();
        loginUser.setUserId(user.getId());
        loginUser.setUserType(client.getClientKey());
        loginUser.setUsername(user.getUsername());
        loginUser.setClientKey(client.getClientKey());
        loginUser.setDeviceType(client.getDeviceType());
        loginUser.setRoles(new ArrayList<>());
        return loginUser;
    }


    /**
     * 校验验证码
     *
     * @param username 用户名
     * @param code     验证码
     * @param uuid     唯一标识
     */
    private void validateCaptcha(String username, String code, String uuid) {
        String verifyKey = GlobalConstants.CAPTCHA_CODE_KEY + StringUtils.blankToDefault(uuid, "");
        String captcha = RedisUtils.getCacheObject(verifyKey);
        RedisUtils.deleteObject(verifyKey);
        if (captcha == null) {
            loginService.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.expire"));
            throw new CaptchaExpireException();
        }
        if (!code.equalsIgnoreCase(captcha)) {
            loginService.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.error"));
            throw new CaptchaException();
        }
    }

    private SysUserVo loadUserByUsername(String username) {
        SysUserVo user = sysUserMapper.selectVoOne(new LambdaQueryWrapper<SysUser>().eq(SysUser::getUserName, username));
        if (ObjectUtil.isNull(user)) {
            log.info("登录用户：{} 不存在.", username);
            throw new UserException("user.not.exists", username);
        } else if (UserStatus.DISABLE.getCode().equals(user.getStatus())) {
            log.info("登录用户：{} 已被停用.", username);
            throw new UserException("user.blocked", username);
        }
        return user;
    }

}
